package com.xuan.pmh.activity;

import java.util.ArrayList;
import java.util.Map;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.xuan.pmh.R;
import com.xuan.pmh.bean.Paper;
import com.xuan.pmh.bean.Question;
import com.xuan.pmh.item.QuestionItem;
import com.xuan.pmh.util.FinalValue;
import com.xuan.pmh.util.ToastUtil;

/**
 * @author xuan 2014-10-30
 * 
 */
public class CreatePaperActivity extends HttpActivity {

	private QuestionItem questionItem;
	private LinearLayout llQuestion;
	private Button btAdd, btDelete, btFinish,btReturn;
	private EditText etInstructions;

	@Override
	public void afterPost(String result, int requestCode,
			Map<String, String> request) {
		// TODO Auto-generated method stub
		gsonBean = getGsonBean(result);
		if(gsonBean.state == FinalValue.SUCCESS){
			ToastUtil.show(this, "创建成功");
			this.finish();
		}else{
			ToastUtil.show(this, "创建失败");
		}
	}

	@Override
	public int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_create_paper;
	}

	@Override
	public void setUI() {
		// TODO Auto-generated method stub
		questionItem = new QuestionItem(inflater);

		llQuestion = (LinearLayout) findViewById(R.id.llQuestion);
		btAdd = (Button) mFindViewAndSetOnClick(R.id.btAdd);
		btDelete = (Button) mFindViewAndSetOnClick(R.id.btDelete);
		btFinish = (Button) mFindViewAndSetOnClick(R.id.btFinish);
		btReturn = (Button) mFindViewAndSetOnClick(R.id.btReturn);
		etInstructions = (EditText) findViewById(R.id.etInstruction);
		
	}

	@Override
	public void OnClickListener(View view) {
		// TODO Auto-generated method stub
		int count = llQuestion.getChildCount();
		switch (view.getId()) {
		case R.id.btDelete:
			if (count > 0) {
				llQuestion.removeViewAt(count - 1);
			}
			break;
		case R.id.btAdd:
			llQuestion.addView(questionItem.createQuestionEdit(2, "问题"
					+ (count + 1)));
			break;
		case R.id.btFinish:
			Paper paper = new Paper();
			paper.instructions = getEditTextString(etInstructions);
			paper.questions = new ArrayList<Question>();
			for (int i = 0; i < llQuestion.getChildCount(); i++) {
				Question q = questionItem.getQuestionEdit(llQuestion
						.getChildAt(i));
				paper.questions.add(q);
			}
			paramsList.clear();
			paramsList.put("param", gson.toJson(paper));
			addPostRequest("createPaper", paramsList, 0);
			sendPostRequest();
			break;
		case R.id.btReturn:
			this.finish();
			break;
		}
	}

}
